package com.wyzt.item.web;

import com.wyzt.common.dto.CartDTO;
import com.wyzt.common.vo.PageResult;
import com.wyzt.item.bo.SpuBo;
import com.wyzt.item.pojo.Sku;
import com.wyzt.item.pojo.Spu;
import com.wyzt.item.pojo.SpuDetail;
import com.wyzt.item.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("spu/page")
    public ResponseEntity<PageResult<SpuBo>> querySpuByPage(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "saleable", required = false) Boolean saleable

    ) {
        return ResponseEntity.ok(goodsService.querySpuByPage(page, rows, saleable, key));
    }

    @PostMapping("goods")
    public ResponseEntity<Void> saveGoods(@RequestBody SpuBo spubo) {
        goodsService.saveGoods(spubo);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("goods/spu/detail/{id}")
    public ResponseEntity<SpuDetail> querySpuDetailById(@PathVariable("id") Long id) {

        return ResponseEntity.ok(goodsService.querySpuDetailById(id));
    }

    @GetMapping("goods/sku/list")
    public ResponseEntity<List<Sku>> querySkuListById(@RequestParam("id") Long id) {
        return ResponseEntity.ok(goodsService.querySkuListById(id));
    }

    @GetMapping("spu/{id}")
    public ResponseEntity<Spu> querySpuById(@PathVariable("id") Long id) {
        Spu spu = this.goodsService.querySpuById(id);
        if (spu == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(spu);
    }

    @GetMapping("spuBo/{id}")
    public ResponseEntity<SpuBo> querySpuBoById(@PathVariable("id") Long id) {
        SpuBo spuBo = this.goodsService.querySpuBoById(id);
        if (spuBo == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(spuBo);
    }

    /**
     * 减库存
     *
     * @param carts
     * @return
     */
    @PostMapping("stock/decrease")
    public ResponseEntity<Void> decreaseStock(@RequestBody List<CartDTO> carts) {
        goodsService.decreaseStock(carts);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

}
